package com.xjc.market.acct.biz;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Example;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xjc.infra.db.Pager;
import com.xjc.infra.entity.ExecuteState;
import com.xjc.infra.entity.QueryResult;
import com.xjc.infra.entity.SessionContext;
import com.xjc.infra.exception.IFSException;
import com.xjc.market.acct.entity.table.AcOperator;
import com.xjc.market.acct.mapper.AcOperatorMapper;
import com.xjc.market.frame.base.BaseTBiz;
import com.xjc.market.frame.entity.Constant;
import com.xjc.market.frame.util.FrameUtil;
/**
 * 操作员biz
 * @author liangcz
 * @Date   2017年9月12日 上午10:51:04
 * @version 1.0
 */
@Service
public class AcOperatorBiz extends BaseTBiz<AcOperator>{
	@Autowired
	AcOperatorMapper acOperatorMapper;
	/**
	 * 查询操作员信息列表
	 * @author liangcz
	 * @date   2017年9月13日 下午5:49:22
	 * @return QueryResult
	 */
	public QueryResult inquiryAcOperatorList(AcOperator acOperator,Pager pager){
		QueryResult queryResult = new QueryResult();
		PageHelper.startPage(pager.getPageNumber(), pager.getPageCount());
		Example example = new Example(AcOperator.class);
		Example.Criteria criteria = example.createCriteria();
		if(StringUtils.isNotBlank(acOperator.getUserid())){
			criteria.andCondition("userid = ", acOperator.getUserid());
		}
		if(StringUtils.isNotBlank(acOperator.getOperatorName())){
			criteria.andLike("operatorName", "%" + acOperator.getOperatorName() + "%");
		}
		List<AcOperator> list = acOperatorMapper.selectByExample(example);
		PageInfo<AcOperator> pageInfo = new PageInfo<AcOperator>(list);
		pager.setRecordCount((int) pageInfo.getTotal());
		queryResult.setPager(pager);
		queryResult.setList(list);
		return queryResult;
	} 
	/**
	 * 根据userid或者phone查找操作员
	 * @author liangcz
	 * @date   2017年9月20日 下午2:15:33
	 * @return List<AcOperator>
	 */
	public List<AcOperator> inquiryAcOperatorList(String userid,String phone){
		Example example = new Example(AcOperator.class);
        Example.Criteria criteria1 = example.createCriteria();
        criteria1.andCondition("userid = ", userid);
        // Example.Criteria criteria2 = example.createCriteria();
        // criteria2.andCondition("phone = ", phone);
        criteria1.orCondition("phone = ", phone);
        List<AcOperator> list = acOperatorMapper.selectByExample(example);
        return list;
	}
	/**
	 * 保存操作员信息(新增/修改)
	 * @author liangcz
	 * @date   2017年9月21日 下午2:59:51
	 * @return void
	 */
	public void saveAcOperator(SessionContext session,AcOperator acOperator){
		ExecuteState state = FrameUtil.getSuccessExcuteState();
		try {
			String userid = acOperator.getUserid();
			String phone = acOperator.getPhone();
			String pwd = acOperator.getPwd();
			if(StringUtils.isBlank(userid)){
				throw new IFSException("AcOperatorBiz.saveAcOperator.01", "用户名不能为空");
			}
			Long operatorId = acOperator.getOperatorId();
			if(operatorId != null){
				acOperator.setDatModify(new Date());
				AcOperator acOperatorSel = acOperatorMapper.selectByPrimaryKey(acOperator.getOperatorId());
				if(acOperatorSel == null){
					throw new IFSException("AcOperatorBiz.saveAcOperator.02", "更新失败，客户不存在");
				}
				if(!pwd.equals(acOperatorSel.getPwd())){
					String md5Salt = FrameUtil.md5AddSalt(pwd, userid);
					acOperator.setPwd(md5Salt);
				}
				/* 如果客户手机做了修改，检查手机是否被占用 */
				if(StringUtils.isNotBlank(phone) && phone.equals(acOperatorSel.getPhone()) == false){
					Example example = new Example(AcOperator.class);
			        Example.Criteria criteria1 = example.createCriteria();
			        criteria1.andCondition("operator_id != ", acOperatorSel.getOperatorId());
			        criteria1.andCondition("phone = ", phone);
			        int c = acOperatorMapper.selectCountByExample(example);
			        if(c > 0){
			        	throw new IFSException("AcOperatorBiz.saveAcOperator.04", "新手机号码已经被占用");
			        }
				}
				acOperatorMapper.updateByPrimaryKey(acOperator);
				return;
			}
			List<AcOperator> list = inquiryAcOperatorList(userid,phone);
			if(list.size() > 0){
				throw new IFSException("AcOperatorBiz.saveAcOperator.03", "用户名或手机被占用");
			}
			/* 首次注册密码为空，则密码设为默认密码 */
			if(StringUtils.isBlank(pwd)){
				pwd = DigestUtils.md5Hex(Constant.DEFULT_OPERATOR_PWD);
			}
			String md5Salt = FrameUtil.md5AddSalt(pwd, userid);
			acOperator.setPwd(md5Salt);
			acOperator.setStatus(Constant.AcOperator_STATUS_00);
			acOperator.setDatCreate(new Date());
			acOperatorMapper.insert(acOperator);
		} catch (IFSException e) {
			throw e;
		} catch (Exception e) {
			IFSException e1 =  new IFSException(e,"AcOperatorBiz.saveAcOperator.99", "保存操作员信息失败");
			throw e1;
		}
	}
	/**
	 * 删除操作员列表
	 * @param operatorIds 操作员id，以逗号隔开。 如： 1,2,3
	 * @author liangcz
	 * @date   2017年9月22日 下午2:54:39
	 * @return ExecuteState
	 */
	public void deleteAcOperator(SessionContext session,String operatorIds){
		ExecuteState state = FrameUtil.getSuccessExcuteState();
		try {
			Example example = new Example(AcOperator.class);
			List<String> idList = Arrays.asList(operatorIds.split(","));
			if(idList.contains("1")){
				throw new IFSException("AcOperatorBiz.deleteAcOperator.01", "admin不允许删除");
			}
			example.createCriteria().andIn("operatorId", idList);
			acOperatorMapper.deleteByExample(example);
		} catch (IFSException e) {
			throw e;
			// loggerUtil.logError(operatorIds, session, ClassUtil.getAbsoluteMethodName(Thread.currentThread().getStackTrace()), e);
			// state = FrameUtil.transferToExecuteState(e);
		} catch (Exception e) {
			IFSException e1 = new IFSException(e,"AcOperatorBiz.deleteAcOperator.99", "删除操作员信息失败");
			throw e1;
			// state = FrameUtil.transferToExecuteState(e1);
			// loggerUtil.logError(operatorIds, session, ClassUtil.getAbsoluteMethodName(Thread.currentThread().getStackTrace()), e1);
		}
		// return state;
	}
}
